package com.demo.listener;

import com.demo.callback.CallBackDev2_4g;
import com.demo.service.EquipmentDataService;
import com.rfid.bean.*;
import com.rfid.uhf.service.Reader2_4gService;
import com.rfid.uhf.service.impl.Reader2_4gServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 直连模式
 */
@Slf4j
@Component
public class DirectConnectionListener {

    @Value("${ip}")
    private String ip;

    @Value("${port}")
    private Integer port;

    @Autowired
    private EquipmentDataService equipmentDataService;

    private static final ExecutorService POOL= Executors.newFixedThreadPool(3);

    @PostConstruct
    public void init() {
        POOL.submit(()->{
            Reader2_4gService service = new Reader2_4gServiceImpl();
            Reader2_4g reader = service.connect(ip,port,new CallBackDev2_4g(equipmentDataService));
            if(null == reader){
                return;
            }
            log.info("连接成功");
            log.info("开启连续读卡");
            service.beginInv(reader); 	//连续读卡
            log.info("查询版信息");
            log.info(service.queryVersion(reader));

            //有异常，StringIndexOutOfBoundsException
            try {
                log.info("查询Http参数配置");
                Map<String,String> map = service.queryHttpParamConfig(reader);
                for (Object key : map.keySet()) {
                    String httpParam = map.get(key);
                    log.info("key is " + key + " value is " + httpParam);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                //e.printStackTrace();
            }

            try {
                //读卡100秒
                Thread.sleep(1000 * 100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("停止连续读卡");
            service.stopInv(reader);  	//停止连续读卡
            log.info("断开连接,释放当前线程");
            service.disconnect(reader); //断开连接,释放当前线程
            //关闭线程池
            POOL.shutdown();
        });
    }



    }




